package cn.itrip.common;

import cn.itrip.beans.pojo.ItripUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 * @author 滕召伟
 */
@Component
public class ValidationToken {


    /**
     * 保存token到redis
     * @param itripUser 登录用户
     * @return 返回给前端的map集合
     */
    public Map<String,Object> saveToken(ItripUser itripUser,RedisTemplate<String,Object> redisTemplate){
        HashMap<String, Object> data = new HashMap<>();
        String encodeMD5Hex = MD5.stringToMD5(itripUser.getUserCode());
        int randomNum = (int) ((Math.random() * 9 + 1) * 100000);
        //生成token
        String token = "token:PC-"+ encodeMD5Hex + "-" +itripUser.getId() + "-" + itripUser.getUserPassword() + "-" + randomNum;
        // 获得系统当前时间戳
        long genTime = Instant.now().toEpochMilli();
        // 过期的时间戳
        Calendar instance = Calendar.getInstance();
        //获取当前时间
        instance.setTime(new Date());
        //获取两个小时后的时间
        instance.add(Calendar.HOUR,2);
        long expTime = instance.getTime().getTime();
        // 生成有效期
        long expire=60 * 2 * 60;

        redisTemplate.opsForValue().set(token,itripUser,expire,TimeUnit.SECONDS);
        Object o = redisTemplate.opsForValue().get(token);
        System.out.println(o);
        data.put("token",token);
        data.put("genTime",genTime);
        data.put("expTime",expTime);
        return data;
    }

    /**
     * 从redis中获取itripUser
     * @param token redis中token的key
     * @param redisTemplate
     * @return
     */
    public ItripUser getToken(String token, RedisTemplate redisTemplate){
        ItripUser itripUser = (ItripUser)redisTemplate.opsForValue().get(token);
        if (itripUser != null) {
            return itripUser;
        }
        return  null;
    }

    /**
     *  判断token是否存在
     * @param redisTemplate
     * @return
     */
    public boolean existsToken(RedisTemplate redisTemplate, HttpServletRequest request){
        String token = request.getHeader("token");
        Boolean isToken = redisTemplate.hasKey(token);
        return isToken;
    }
}
